import React, { useEffect, useRef, useState } from "react";
import { connectWs, getPrice } from "./api";
import type { StockPrice } from "./types";

export default function App() {
  const [symbol, setSymbol] = useState("AAPL");
  const [price, setPrice] = useState<StockPrice | null>(null);
  const [wsStatus, setWsStatus] = useState("disconnected");
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    getPrice(symbol).then((res) => setPrice(res.data)).catch(() => {});
  }, [symbol]);

  useEffect(() => {
    const ws = connectWs((msg) => {
      if (msg.type === "subscribed") setWsStatus("subscribed");
      if (msg.type === "price_update") setPrice(msg.data);
    });
    wsRef.current = ws;
    ws.onopen = () => setWsStatus("connected");
    ws.onclose = () => setWsStatus("disconnected");
    return () => ws.close();
  }, []);

  const subscribe = () => {
    wsRef.current?.send(JSON.stringify({ symbol }));
  };

  return (
    <div style={{ padding: 16, fontFamily: "system-ui, -apple-system, Segoe UI, Roboto" }}>
      <h2>Stock Ticker (Simulated)</h2>
      <div>
        <input
          value={symbol}
          onChange={(e) => setSymbol(e.target.value.toUpperCase())}
          placeholder="Symbol e.g. AAPL"
          style={{ padding: 8, marginRight: 8 }}
        />
        <button onClick={subscribe} style={{ padding: "8px 12px" }}>订阅</button>
      </div>
      <div style={{ marginTop: 16 }}>
        <div>WebSocket: {wsStatus}</div>
        <div>当前股票: {symbol}</div>
        <div>最新价格: {price ? price.price.toFixed(2) : "-"}</div>
        <div>时间: {price ? new Date(price.ts).toLocaleTimeString() : "-"}</div>
      </div>
    </div>
  );
}